#include <stdio.h>
#include <string.h>
#include "cmsis_os2.h"
#include "ohos_init.h"
#include "wifi_device.h"
#include "wifi_hotspot_config.h"

#include "vue_http_server.h"


static WifiErrorCode wifi_error;
static WifiEvent g_wifiEventHandler = {0};
static void OnHotspotStaJoinHandler(StationInfo *info)
{
    (void)info;
    printf("STA join AP\n");
    return;
}

static void OnHotspotStaLeaveHandler(StationInfo *info)
{
    (void)info;
    printf("HotspotStaLeave:info is null.\n");
    return;
}

static void OnHotspotStateChangedHandler(int state)
{
    printf("HotspotStateChanged:state is %d.\n", state);
    return;
}

static void WiFiInit(void)
{
    printf("<--Wifi Init-->\r\n");
    g_wifiEventHandler.OnHotspotStaJoin = OnHotspotStaJoinHandler;
    g_wifiEventHandler.OnHotspotStaLeave = OnHotspotStaLeaveHandler;
    g_wifiEventHandler.OnHotspotStateChanged = OnHotspotStateChangedHandler;
    wifi_error = RegisterWifiEvent(&g_wifiEventHandler);
    if (wifi_error != WIFI_SUCCESS) {
        printf("register wifi event fail!\r\n");
    } else {
        printf("register wifi event succeed!\r\n");
    }
}

static void Ap_Demo(void)
{
    HotspotConfig ap_config = {
        .ssid = "ESP32_AP",
        .preSharedKey = "123456789",
        .securityType = WIFI_SEC_TYPE_PSK,
    };
    if (SetHotspotConfig(&ap_config) != WIFI_SUCCESS) {
        printf("SetHotspotConfig failed, wifi_error = %d\n", wifi_error);
        return;
    }
    if (EnableHotspot() != WIFI_SUCCESS) {
        printf("EnableHotspot failed, wifi_error = %d\n", wifi_error);
        return;
    }
    return;
}

// 禁用Wi-Fi AP模式
static void DisableWifiAp(void)
{
    printf("Disabling Wi-Fi AP mode...\n");
    if (DisableHotspot() != WIFI_SUCCESS)
    {
        printf("Disable hotspot failed, error code: %d\n", wifi_error);
        return;
    }
    printf("Wi-Fi AP mode disabled\n");
}

void WifiApTask(void)
{
    WiFiInit();
    Ap_Demo();
    start_http_server();
    osDelay(30000);
    printf("going to disable wifi AP...");
    osDelay(3000);
    DisableWifiAp();
    osDelay(10000);
    printf("going to enable wifi AP...");
    osDelay(1000);
    Ap_Demo();
    while (1) {
      osDelay(100);
    }
}

void WifiApDemo(void)
{
    osThreadAttr_t attr;
    attr.name = "WIFI_AP_TASK";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 0x1000;
    attr.priority = 25;

    if (osThreadNew((osThreadFunc_t)WifiApTask, NULL, &attr) == NULL) {
        printf("Failed to create thread!\n");
    }
}

APP_FEATURE_INIT(WifiApDemo);